package com.op.teachingliteapp.util.network;

import java.security.KeyStore;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.op.teachingliteapp.util.ToastUtils;

public class NetworkUtils {
	private static final int TIMEOUT = 30000;

	public static HttpResponse HttpPostsWithResponse(String url, List<NameValuePair> params, List<NameValuePair> headers) throws Exception {
		HttpPost request = new HttpPost(url);
		HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
		request.setEntity(entity);
		if (!(headers == null || headers.isEmpty())) {
			for (NameValuePair header : headers) {
				request.setHeader(header.getName(), header.getValue());
			}
		}
		HttpClient httpClient = new DefaultHttpClient();
		HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), TIMEOUT);
		HttpResponse httpResponse = httpClient.execute(request);
		if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
			throw new RuntimeException("read url failed");
		} else {
			return httpResponse;
		}
	}

	public static String HttpPosts(String url, List<NameValuePair> params) throws Exception {
		return HttpPosts(url, params, null);
	}

	public static String HttpPosts(String url, List<NameValuePair> params, List<NameValuePair> headers) throws Exception {
		String result = "";
		HttpPost request = new HttpPost(url);
		HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
		request.setEntity(entity);
		if (!(headers == null || headers.isEmpty())) {
			for (NameValuePair header : headers) {
				request.setHeader(header.getName(), header.getValue());
			}
		}
		HttpClient httpClient = getNewHttpClient();
		HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), TIMEOUT);
		HttpResponse httpResponse = httpClient.execute(request);
		if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
			throw new RuntimeException("read url failed");
		} else {
			result = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
		}
		return result;
	}

	public static String HttpGets(String url) throws Exception {
		String result = "";
		HttpGet httpGet = new HttpGet(url);
		HttpClient httpClient = getNewHttpClient();
		HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), TIMEOUT);
		HttpResponse httpResponse = httpClient.execute(httpGet);
		if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
			throw new RuntimeException("read url failed");
		} else {
			result = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
		}
		return result;
	}

	public static HttpClient getNewHttpClient() {
		try {
			KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
			trustStore.load(null, null);

			SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
			sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

			HttpParams params = new BasicHttpParams();
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

			SchemeRegistry registry = new SchemeRegistry();
			registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
			registry.register(new Scheme("https", sf, 443));

			ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

			return new DefaultHttpClient(ccm, params);
		} catch (Exception e) {
			return new DefaultHttpClient();
		}
	}

	/**
	 * wifi是否打开
	 */
	public static boolean isWifiConnected(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		if (wifiNetworkInfo.isConnected()) {
			return true;
		}

		return false;
	}

	/*
	 * 2015/7/8 陈宇瀚 判断是否有3G链接
	 */
	public static boolean isGSMConnected(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkINfo = cm.getActiveNetworkInfo();
		if (networkINfo != null && networkINfo.getType() == ConnectivityManager.TYPE_MOBILE) {
			return true;
		}
		return false;
	}

	public static boolean isNetworkAvailable(Context context, boolean showToast) {
		boolean available = isWifiConnected(context) || isGSMConnected(context);
		if (!available && showToast) {
			ToastUtils.show(context, "没有网络连接，请打开您的蜂窝数据或者Wifi...");
		}
		return available;
	}

	public static boolean isNetworkAvailable(Context context) {
		boolean available = isWifiConnected(context) || isGSMConnected(context);
		return available;
	}

}
